#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
#include <string.h>
#include <sys/mman.h>
#include <assert.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>

using namespace std;
using namespace cv;

#define  IMAGE_W 800
#define  IMAGE_H 1067

#define  FILE_NAME "output24.rgb"

int convert_rgb24_to_bgr24_buffer(unsigned char *rgb, unsigned char *bgr,
		unsigned int width, unsigned int height) {
	unsigned char *ptr = rgb;
	unsigned char *ptr2 = bgr;
	int r, g, b;
	int i = 0;
	while (i < width * height) {
		i++;
		r = *(ptr++);
		g = *(ptr++);
		b = *(ptr++);

		*(bgr++) = b;
		*(bgr++) = g;
		*(bgr++) = r;
	}
	return 0;
}

/**
 * 	 rgb24 to bgr24 to jpg.
 *   ffmpeg -i in.jpg -pix_fmt rgb24  output24.rgb  -y
 *   ffmpeg  -pix_fmts
 *
 */
int main() {
	int ret;
	int fd = open(FILE_NAME, O_RDONLY);
	if (ret == -1) {
		perror("open");
		return -1;
	}
	unsigned char rgb24[IMAGE_W * IMAGE_H * 3 + 1000];
	ret = read(fd, rgb24, IMAGE_W * IMAGE_H * 3 + 1000);
	if (ret == -1) {
		perror("read");
		return -1;
	}
	assert(ret == IMAGE_W * IMAGE_H * 3);
	char bgr24[IMAGE_W * IMAGE_H * 3];
	convert_rgb24_to_bgr24_buffer((unsigned char*) rgb24,
			(unsigned char*) bgr24,
			IMAGE_W, IMAGE_H);
	Mat image(IMAGE_H, IMAGE_W, CV_8UC3, bgr24);
	if (imwrite("output.jpg", image)) {
		cout << "success save to output.jpg" << endl;
	} else {
		perror("imwrite");
	}
	return 0;
}
